﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace RuoVea.ExUtil.Validate;

/// <summary>
/// 描 述：时间
/// </summary>
public sealed class DateAttribute : ValidationAttribute
{
    /// <summary>
    /// 时间验证规则
    /// </summary>
    public DateAttribute()
    {
        this.ErrorMessage = "{0}:请输入正确的时间格式!";
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="msg">异常消息</param>
    public DateAttribute(string msg)
    {
        this.ErrorMessage = msg;
    }

    /// <summary>
    /// 证请求结果
    /// </summary>
    /// <param name="value">校验内容</param>
    /// <param name="validationContext">报错指定对象</param>
    /// <returns>证请求结果的容器</returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            Regex r = new Regex(@"^(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$");
            if (!r.IsMatch(value + ""))
            {
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
        }
        return ValidationResult.Success;
    }
}
